App.converter = new Showdown.converter();

App.ContentStore = new Opal.Store({
    fields: ["id","code","body","created_at","updated_at"],
    url: App.contextPath + "/content"    
});

App.ContentView = new Opal.View({
    templateName: "#content-template",
    rootElement: "#content-container"
});

ContentController = Opal.Controller.extend({
    contentData: null,
    init: function (params) {
        this._super();
        this.reload(params);
    },
    reload: function(params,callback) {
        var me = this;
        App.ContentView.showLoader();
        App.ContentStore.load(params,function(data) {
           me.contentData = data;
           App.ContentView.hideLoader();
           App.ContentView.context = { 
               category: data.category,
               body: App.converter.makeHtml(data.body),
               code: data.code,
               title: data.title
           };
           App.ContentView.show("clean-append");

           
           if (callback != undefined) {
               callback();
           }
        });
    },
    showEditor: function() {
        if (this.contentData) {
            Opal.$(".show-editor").hide();
            Opal.$(".save-editor").show();
            Opal.$(".cancel-editor").show();
            Opal.$(".content-body").empty();
            var editor = Opal.$('<textarea class="editor"></textarea>').val(this.contentData.body);
            Opal.$(".content-body").append(editor);
        }
    },
    saveEditor: function() {
        var me = this;
        var editor = Opal.$(".editor");
        
        me.contentData.body = editor.val();
        
        Opal.$.post("/content/save/"+this.contentData.category_id,{"body": this.contentData.body,"title": this.contentData.title},function (data) {
            
            Opal.$(".show-editor").show();
            Opal.$(".save-editor").hide();
            Opal.$(".cancel-editor").hide();            
            editor.remove();
            Opal.$(".content-body").append(App.converter.makeHtml(me.contentData.body));
        });
    },
    cancelEditor: function() {
        if (this.contentData) {
            Opal.$(".show-editor").show();
            Opal.$(".save-editor").hide();
            Opal.$(".cancel-editor").hide();
            Opal.$(".content-body").empty();
            var editor = App.converter.makeHtml(this.contentData.body);
            Opal.$(".content-body").append(editor);
        }        
    }
});

